from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login

from .forms import *
from django.contrib.auth.decorators import login_required
from django.views.decorators.cache import cache_page
from notifications.signals import notify

from .models import User, UserFollow
from trend.models import TrendList
from favorite.models import MusicFavorite, PostFavorite
# Create your views here.

def user_login(request):
    """
    用户登录视图
    """
    # 获取重定向url
    redirect_to = request.POST.get('next',request.GET.get('next', ''))

    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        # 检查用户是否存在
        user = authenticate(request,username=username,password=password)

        if user:
            # 如果存在该用户,则执行内置的login函数进行用户登录
            login(request, user)
            # 设置用户session过期时间,秒为单位
            request.session.set_expiry(600)

            if redirect_to:
                return redirect(redirect_to)
            else:
                return redirect('music:index')
        else:
            form = LoginForm()

            return render(request, 'user/login.html', context={'form': form, 'next': redirect_to, 'error': '用户名或密码错误'})

    else:
        form = LoginForm()
        return render(request, 'user/login.html', context={'form': form, 'next': redirect_to})


def register(request):
    """
    用户注册视图
    """
    # redirect_to = request.POST.get('next', request.GET.get('next', ''))

    if request.method == 'POST':
        form = RegisterForm(request.POST)

        if form.is_valid():
            username = form.cleaned_data['username']
            namefilter = User.objects.filter(username=username)
            if namefilter:
                return render(request, 'user/register.html', {'error': '该昵称已被注册', 'form': form})
            else:
                pwd = form.cleaned_data['pwd']
                pwd_again = form.cleaned_data['pwd_again']
                if pwd == pwd_again:
                    username = form.cleaned_data['username']
                    password = pwd_again
                    sex = form.cleaned_data['sex']
                    age = form.cleaned_data['age']
                    phone_number = form.cleaned_data['phone_number']
                    email = form.cleaned_data['email']
                    is_auth = 0

                    try:
                        user = User.objects.create_user(username=username, password=password, sex=sex, age=age, phone_number=phone_number, email=email, is_auth=is_auth)
                        user.save()
                    except Exception:
                        error = '该邮箱已被注册'
                        return render(request, 'user/register.html', {'error': error, 'form': form})

                else:
                    return render(request, 'user/register.html', {'error': '两次输入密码不一致', 'form': form})

            # if redirect_to:
            return redirect('user:user_login')
            # else:
            #     return redirect('music:index')

    else:
        form = RegisterForm()

    return render(request, 'user/register.html', context={'form': form})


@login_required
def edit_profile(request):
    """
    用户资料修改视图
    """
    redirect_to = request.POST.get('next', request.GET.get('next', ''))

    if request.method == 'POST':
        form = EditForm(request.POST, request.FILES, instance=request.user)
        if form.is_valid():
            username = form.cleaned_data['username']

            if username != request.user.username:
                filter = User.objects.filter(nickname=username)
                if filter:
                    return render(request, 'user/edit_profile.html', context={'form': form, 'error': '该昵称已存在', 'next': redirect_to})
            form.save()

            trend_content = '修改了个人资料'
            trend = TrendList.objects.create(user=request.user, content=trend_content)
            trend.save()

            if redirect_to:
                return redirect(redirect_to)
            else:
                return redirect('music:index')

    form = EditForm(instance=request.user)

    return render(request, 'user/edit_profile.html', context={'form': form, 'next': redirect_to})


# @cache_page(60 * 5)
@login_required
def show_profile(request):
    """
    个人中心视图
    """
    trend_list = TrendList.objects.filter(rec_user=request.user).order_by('-trend_time')
    f_music_list = MusicFavorite.objects.filter(user=request.user)
    f_post_list = PostFavorite.objects.filter(user=request.user)

    context = {'trend_list': trend_list,
               'f_music_list': f_music_list,
               'f_post_list': f_post_list}

    return render(request, 'user/profile.html', context=context)


@login_required
def certification(request):
    """
    用户实名认证视图
    """
    # 改为ajax进行实名认证提交
    if request.method == 'POST':
        user = request.user
        id_card = request.POST.get('id_card')
        real_name = request.POST.get('real_name')
        id_card_positive = request.FILES.get('id_card_positive')
        id_card_back = request.FILES.get('id_card_back')

        # 判断用户是否填写表单所有信息
        is_null = list(filter(lambda x: len(x)==0,[id_card, real_name, id_card_positive, id_card_back]))
        if is_null:
            return JsonResponse({'status': 'warning', 'msg': '请填写完整所有信息!'})

        # 检查用户是否已经实名
        auth_filter = User.objects.filter(id=user.id, is_auth=1)
        if auth_filter:
            return JsonResponse({'status': 'warning', 'msg': '您已经实名认证过了!'})

        # 检查用户是否重复提交认证
        cert_filter = Certification.objects.filter(user=user)
        if cert_filter:
            return JsonResponse({'status': 'warning', 'msg': '请不要重复提交!'})

        try:
            cert = Certification()
            cert.user = user
            cert.id_card = id_card
            cert.real_name = real_name
            cert.id_card_positive = id_card_positive
            cert.id_card_back = id_card_back

            cert.save()
        except Exception:
            return JsonResponse({'status': 'error', 'msg': '提交申请失败，请重试!'})

        return JsonResponse({'status': 'success', 'msg': '提交申请成功，等待管理员审核!'})

    return render(request, 'user/certification.html')


@login_required
def show_another(request, pk):
    """
    查看其他用户主页视图
    """
    # 获取要访问的用户实例和其动态
    follow_user = User.objects.get(id=pk)
    trend_list = TrendList.objects.filter(rec_user_id=pk)
    # 判断该用户是否是当前请求用户的粉丝
    is_fan = UserFollow.objects.filter(follow=follow_user, fan=request.user)
    if follow_user == request.user:
        return redirect('/show_profile')
    else:
        # 如果发送请求的用户是访问用户对象的粉丝,则在前端页面中显示为已关注
        if is_fan:
            is_fan = True
        else:
            is_fan = False

        # 访问用户动态更新
        TrendList.objects.create(user=request.user, rec_user=follow_user, content='访问了你的主页').save()

        context = {'follow_user': follow_user, 'trend_list': trend_list, 'is_fan': is_fan}

        return render(request, 'user/show_another.html', context=context)


@csrf_exempt
@login_required
def user_follow(request):
    """
    用户关注视图
    """
    if request.method == 'POST':
        follow_id = request.POST.get('follow_id')
        fan_id = request.POST.get('fan_id')

        if follow_id and fan_id:
            # 在数据库中查询发送请求的用户是否已经关注该用户
            user_filter = UserFollow.objects.filter(follow_id=follow_id, fan_id=fan_id)
            if user_filter:
                # 如果已经关注用户,则从数据库中移除该记录,并提示用户已取消关注
                user_filter.delete()
                follow_user = User.objects.filter(id=follow_id)
                _fan_count = follow_user[0].fan_count
                follow_user.update(fan_count=_fan_count - 1)
                fan_count = follow_user[0].fan_count

                request.user.follow_count = request.user.follow_count - 1
                request.user.update()

                status = 'failed'
            else:
                UserFollow.objects.create(follow_id=follow_id, fan_id=fan_id)
                follow_user = User.objects.filter(id=follow_id)
                _fan_count = follow_user[0].fan_count
                follow_user.update(fan_count=_fan_count + 1)
                fan_count = follow_user[0].fan_count

                request.user.follow_count = request.user.follow_count + 1
                request.user.update()

                notify.send(request.user, recipient=follow_user, verb='您新增了一位粉丝!')

                status = 'ok'
        else:
            status = 'failed'
            fan_count = 0
        return JsonResponse({'status': status, 'fan_count': fan_count})
